﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Task.Logic;
using Task.Entity;
using Ultimus.WFServer;
using System.Data;
using App.Data;

namespace Task
{
    public partial class ESI_TBConfigDetail : System.Web.UI.Page
    {
        ESI_TBConfigLogic _logic = new ESI_TBConfigLogic();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtProcessName.Text = Request.QueryString["ProcessName"];
                hidStepName.Value = Request.QueryString["StepName"];


                BindDropdownlist();
                if (!string.IsNullOrEmpty(hidStepName.Value))
                {
                    for (int i = 0; i < ddlStepName.Items.Count; i++)
                    {
                        if (ddlStepName.Items[i].Text.ToUpper().Trim() == hidStepName.Value.ToUpper().Trim())
                        {
                            ddlStepName.Items[i].Selected = true;
                        }
                    }
                }

                LoadMapFromDB();
            }
        }

        void LoadMapFromDB()
        {
            string where = " and ProcessName='" + txtProcessName.Text + "' and StepName='" + ddlStepName.SelectedValue + "'";

            List<ESI_TBConfigEntity> dt = _logic.GetList(where);
            if (dt != null && dt.Count > 0)
            {
                foreach (ESI_TBConfigEntity row in dt)
                {
                    List<MappingClass> map = MappingClassInstance;
                    map.Add(new MappingClass(row.TABLE_NAME, row.COLUMN_NAME, row.SSL_VARNAME, row.IS_SUBTABLE == "1" ? "Y" : "N"));
                    MappingClassInstance = map;
                }
                BindMapGrid();
            }
            else
            {
                MappingClassInstance = new List<MappingClass>();
                BindMapGrid();
            }
        }

        Variable[] GetMainSS()
        {
            Variable[] vars = null;
            string taskID=_logic.GetInitTaskID(txtProcessName.Text);
              if (!string.IsNullOrEmpty(taskID))
            {
                Ultimus.WFServer.Task t = new Ultimus.WFServer.Task();
                t.InitializeFromInitiateTaskId("", taskID);
                string error = "";
                t.GetAllTaskVariables(out vars, out error);
            }
            return vars;
        }

        void BindDropdownlist()
        {
            //step
            
            DataTable dt = DataAccess.Instance().ExecuteDataTable("select top 1 PROCESSVERSION,MAINSS from PROCESSES where  ProcessName='" + txtProcessName.Text + "' order by PROCESSVERSION desc");
            if (dt != null && dt.Rows.Count > 0)
            {
                dt = DataAccess.Instance().ExecuteDataTable("select '' as STEPLABEL union all select STEPLABEL from PROCESSSTEPS where  ProcessName='" + txtProcessName.Text + "' and  PROCESSVERSION=" + dt.Rows[0][0].ToString());
                ddlStepName.DataTextField = "STEPLABEL";
                ddlStepName.DataValueField = "STEPLABEL";
                ddlStepName.DataSource = dt;
                ddlStepName.DataBind();
            }

            //table

            dt = DataAccess.Instance("BusinessDB").ExecuteDataTable(" select * from sysobjects where xtype='U'  order by name");
            if (dt != null && dt.Rows.Count > 0)
            {
                ddlTableName.DataTextField = "name";
                ddlTableName.DataValueField = "id";
                ddlTableName.DataSource = dt;
                ddlTableName.DataBind();
                ddlTableName_SelectedIndexChanged(null, null);
            }

            //ss
            Variable[] vars = GetMainSS();
            ddlSSLVarName.DataTextField = "strVariableName";
            ddlSSLVarName.DataValueField = "strVariableName";
            ddlSSLVarName.DataSource = vars;
            ddlSSLVarName.DataBind();

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ESI_TBConfigList.aspx?ProcessName=" + txtProcessName.Text);
        }
        protected void ddlTableName_SelectedIndexChanged(object sender, EventArgs e)
        {

            DataTable dt = DataAccess.Instance("BusinessDB").ExecuteDataTable(" select * from syscolumns where id= " + ddlTableName.SelectedValue);
            if (dt != null && dt.Rows.Count > 0)
            {
                ddlColumnName.DataTextField = "name";
                ddlColumnName.DataValueField = "name";
                ddlColumnName.DataSource = dt;
                ddlColumnName.DataBind();
            }
        }
        protected void btnMapping_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ddlColumnName.SelectedValue))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('列名不能为空');</script>");
                return;
            }
            if (string.IsNullOrEmpty(ddlSSLVarName.SelectedValue))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('电子表格变量不能为空');</script>");
                return;
            }

            List<MappingClass> cls = MappingClassInstance;
            string tableName = ddlTableName.SelectedItem.Text;
            string columnName = ddlColumnName.SelectedValue;
            bool flag = cls.Exists(delegate(MappingClass cc)
            {
                if (cc.TableName.Trim().ToUpper() == tableName.Trim().ToUpper() && cc.ColumnName.Trim().ToUpper() == columnName.Trim().ToUpper())
                {
                    return true;
                }
                return false;
            });
            if (flag)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('列名不能重复');</script>");
                return;
            }
            cls.Add(new MappingClass(tableName, columnName, ddlSSLVarName.SelectedValue, cbxIsSubTable.Checked ? "Y" : "N"));

            MappingClassInstance = cls;

            BindMapGrid();
        }

        void BindMapGrid()
        {
            Repeater1.DataSource = MappingClassInstance;
            Repeater1.DataBind();

            ShowMappedGrid();
        }


        List<MappingClass> MappingClassInstance
        {
            get
            {
                if (ViewState["MappingClass"] == null)
                {
                    ViewState["MappingClass"] = new List<MappingClass>();
                }
                try
                {
                    return (List<MappingClass>)ViewState["MappingClass"];
                }
                catch
                {
                    return new List<MappingClass>();
                }
            }
            set
            {
                ViewState["MappingClass"] = value;
            }
        }

        void ShowMappedGrid()
        {
            if (MappingClassInstance.Count > 0)
            {
                trMapped.Visible = true;
                trMappedGrid.Visible = true;
            }
        }

        [Serializable]
        public class MappingClass
        {

            public MappingClass(string tableName, string columnName, string varName, string is_subtable)
            {
                TableName = tableName;
                ColumnName = columnName;
                VarName = varName;
                Is_SubTable = is_subtable;
            }

            string _tableName;

            public string TableName
            {
                get { return _tableName; }
                set { _tableName = value; }
            }

            private string _columnName;

            public string ColumnName
            {
                get { return _columnName; }
                set { _columnName = value; }
            }

            private string _varName;

            public string VarName
            {
                get { return _varName; }
                set { _varName = value; }
            }

            string _id = Guid.NewGuid().ToString();

            public string Id
            {
                get { return _id; }

            }

            string _Is_SubTable;

            public string Is_SubTable
            {
                get { return _Is_SubTable; }
                set { _Is_SubTable = value; }
            }
        }


        protected void btnMappingDelete_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in Repeater1.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox cb = item.FindControl("chk") as CheckBox;
                    if (cb.Checked)
                    {
                        TextBox txt = item.FindControl("txtId") as TextBox;
                        MappingClassInstance.RemoveAll(delegate(MappingClass cls)
                        {
                            if (cls.Id == txt.Text)
                            {
                                return true;
                            }
                            return false;
                        });
                        MappingClassInstance = MappingClassInstance;

                    }
                }
            }
            BindMapGrid();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ddlStepName.SelectedValue))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('步骤名称不能为空');</script>");
                return;
            }
            if (MappingClassInstance.Count == 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('映射关系不能为空');</script>");
                return;
            }


            string sql = string.Format("delete from T_ESI_TB_CONFIG where ProcessName='{0}' and StepName='{1}';", txtProcessName.Text, ddlStepName.SelectedValue);
            foreach (MappingClass map in MappingClassInstance)
            {
                string text = "insert into T_ESI_TB_CONFIG(GUID, PROCESSNAME,  STEPNAME,  TABLE_NAME, " +
                    "COLUMN_NAME,  SSL_VARNAME, IS_SUBTABLE,  IS_ENABLED )";
                text += " values(newid(),'{0}','{1}','{2}','{3}','{4}','{5}',1);";
                sql = sql + string.Format(text, txtProcessName.Text, ddlStepName.SelectedValue, map.TableName,
                    map.ColumnName, map.VarName, map.Is_SubTable == "Y" ? 1 : 0);
            }

            DataAccess.Instance("BusinessDB").ExecuteNonQuery(sql);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('保存成功');</script>");
        }
        protected void ddlStepName_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadMapFromDB();
        }
    }
}